package org.example.factory.support;

import cn.hutool.core.util.StrUtil;
import org.example.exception.BeansException;
import org.example.factory.DisposableBean;
import org.example.factory.config.BeanDefinition;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: luyg
 * @Date: 2024/09/09/1:11
 * @Description:
 */
public class DisposableBeanAdapter implements DisposableBean {
    private final Object bean;
    private final String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws BeansException {
        if(bean instanceof DisposableBean){
            ((DisposableBean) bean).destroy();
        }
        try {
            if (StrUtil.isNotEmpty(destroyMethodName) && !(bean instanceof DisposableBean && "destroy".equals(this.destroyMethodName))) {
                Method method = bean.getClass().getMethod(destroyMethodName);
                method.invoke(destroyMethodName);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

    }
}
